<?php
/**********************************************************
Copyright (c) 2011 Wayne State University Library System
Licensed under the MIT License.
Redistributions of files must retain the above copyright notice.

This software is distributed in the hope that it will be useful, 
but WITHOUT ANY WARRANTY; without even the implied warranty
of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

MapIt!
http://www.lib.wayne.edu/MapIt!/
http://code.google.com/XXXX
contact: Paul Gallagher, Developer Librarian WSULS
email: paul.gallagher@wayne.edu
***********************************************************/
require_once('admin/config/config.inc.php');
require_once('MDB2.php');
require_once('lib/functions.php');

//enable debug options
if ($debug == true) {
	ini_set('display_errors',1);
	error_reporting(E_ALL);	
}


//#####################  Page Logic  #############################
//sanitize the array
$clean = array();
foreach ($_GET as $key => $value) {
	$clean[$key] = mysql_real_escape_string($value);
}

//make sure we have a location, if not redirect to the reference page
if ($clean["location"] == "" || strlen($clean["location"]) == 0 )	{
		header( 'Location:' . $errorPage);  //no location, FAIL
}

// create MDB2 instance
$mdb2 = MDB2::factory($dsn);
$mdb2->setFetchMode(MDB2_FETCHMODE_ASSOC);
$query = "SELECT * FROM locations WHERE location_code = '$clean[location]'";
$result = $mdb2->query($query);
$array = $result->fetchAll();
$result->free();
if ($debug == true) {
	print_r($array);
}

if ($clean["call"] != "") {		//callnumber lookup for template
	$nCall = LCCallToNumber($clean['call']);

	//check based on the call number
	$query = "SELECT *, IF(ISNULL(location_subcode), location_code, CONCAT(location_code, location_subcode)) AS location_jointcode FROM locations_calls WHERE location_code = '$clean[location]' AND start_call <= $nCall AND end_call >= $nCall";
	$mdb2 = MDB2::factory($dsn);
	$mdb2->setFetchMode(MDB2_FETCHMODE_ASSOC);
	$result = $mdb2->query($query);
	$array_call = $result->fetchRow();
	
	//get the location
	$query = "SELECT *, IF(ISNULL(location_subcode), location_code, CONCAT(location_code, location_subcode)) AS location_jointcode FROM locations WHERE  IF(ISNULL(location_subcode), location_code, CONCAT(location_code, location_subcode)) = '$array_call[location_jointcode]'";
	$mdb2 = MDB2::factory($dsn);
	$mdb2->setFetchMode(MDB2_FETCHMODE_ASSOC);
	$result = $mdb2->query($query);
	$array = $result->fetchRow();
}
else if(count($array) > 1) {  //two location_codes assigned or call missing...
	header( 'Location:' . $errorPage);	
}
else  {
	$array = $array[0];
}

//-------------- OUTPUT TYPES ------------------//
//types are call_number, static, mapped_to, overlay
switch($array['content_type'])
{
	default:  //if it fails all of the above
		header( 'Location:' . $errorPage);	
	break;
	case 'call_number':		//do callnumber lookup
		if ($array['template'] != "")	{	//check for a template & a valid call range
			//do the image merge function
			$outputImg = displayOverlayImage($array['template'], $array_call['x'], $array_call['y'], $array_call['width'], $array_call['height']);
			
			//set the image var for output
			$output = '<img src="'.$outputImg.'"// alt="This is a map of '.$array['location_name'] . '">';
		}
		else	
		{
			header( 'Location:' . $errorPage);	
		}
	break;
	case 'static':			//display static content
		if ($array["content"] != "")  //make sure there is content
		{					
			$output = $array['content'];	 
		}
		else
		{
			header( 'Location:' . $errorPage);	
		}
	break;
	case 'mapped_to':		//map to another code
		$a = "index.php?location=" . $array["remap_code"];
		header( 'Location: ' . $a );
	break;
	case 'overlay':			//display a dynamic overlay map
		if($array['template'] != "")	{	//check for a template
			//do the image merge function
			$outputImg = displayOverlayImage($array['template'], $array['x'], $array['y'], $array['width'], $array['height']);
			
			//set the image var for output
			$output = '<img src="'.$outputImg.'"// alt="This is a map of '.$array['location_name'] . '">';
		}
		else  {
			header( 'Location:' . $errorPage);	
		}
	break;
}

//do output
include('templates/main.php');





//#####################  FUNCTIONS #############################
//create overlay images
function displayOverlayImage($mapTemplate, $dst_x, $dst_y, $src_w, $src_h)	
{
	$img = 'maps/templates/'.$mapTemplate;				//template
	$imgOutName = substr($mapTemplate, 0, strlen($mapTemplate) - 4) . $dst_x . $dst_y . $src_w . $src_h;		//setup the full image name with the coords
	$imgOutput = 'maps/dynamic/'.$imgOutName.'.gif';					//output
	
	if (file_exists($imgOutput)) {
		return $imgOutput;
	} 
	else {
		//Create the image memory streams
		$dest = imagecreatefromgif($img);							//get the template image
		$src = imagecreatefromgif('maps/templates/overlay.gif');	//get the overlay
		
		//merge the images
		imagecopymerge($dest, $src, $dst_x, $dst_y, 0, 0, $src_w, $src_h, 90);
		$srcw = $src_w / 2;  //get half the width
		$srch = $src_h / 2;  //get half the height
		
		//determine if to put the arrow on the top or side based on width/height
		 //note, the math is funny, and needs a 8px correction show in the ($dst_y + $srch - 8) code
		 if ($src_w > $src_h) {
			//merge on side
			$arrow = imagecreatefromgif('maps/templates/arrowSide.gif');	//get the arrow
			imagecopymerge($dest, $arrow, $dst_x - 40, ($dst_y + $srch - 8), 0, 0, 37, 17, 100);
		 }
		 else  {
			//merge on top
			$arrow = imagecreatefromgif('maps/templates/arrow.gif');	//get the arrow
			imagecopymerge($dest, $arrow, ($dst_x + $srcw - 8), $dst_y - 40, 0, 0, 17, 37, 100);
		 }

		// Output and free from memory
		$image = imagegif($dest,$imgOutput);
		imagedestroy($dest) or die ('failed imageDestroy(1) - this should not happen');
		imagedestroy($src) or die ('failed imageDestroy(2) - this should not happen');
		imagedestroy($arrow) or die ('failed imageDestroy(3) - this should not happen');

	return $imgOutput;
	}
}
